package com.zengdada.authority.config.security.intercept;

import com.zengdada.authority.utils.JsonMessage;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 权限不足时的自定义处理，主要是针对ajax请求
 */
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    private String errorPage;

    public MyAccessDeniedHandler(String errorPage) {
        this.errorPage = errorPage;
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {

        response.setHeader("Content-type", "text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        // is ajax request?
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            try (PrintWriter out = response.getWriter()) {
                out.print(JsonMessage.fail("无操作权限！！！-" + accessDeniedException.getLocalizedMessage(), 403).toJsonString());
            }
        } else {
            if (!response.isCommitted()) {
                if (errorPage != null && !"".equals(errorPage) && errorPage.startsWith("/")) {
                    // Put exception into request scope (perhaps of use to a view)
                    request.setAttribute(WebAttributes.ACCESS_DENIED_403,
                            accessDeniedException);

                    // Set the 403 status code.
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);


                    // forward to error page.
                    RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
                    dispatcher.forward(request, response);
                } else {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN,
                            accessDeniedException.getMessage());
                }
            }
        }
    }

    public void setErrorPage(String errorPage) {
        if ("".equals(errorPage))
            errorPage = null;
        if ((errorPage != null) && !errorPage.startsWith("/")) {
            throw new IllegalArgumentException("errorPage must begin with '/'");
        }
        this.errorPage = errorPage;
    }

}
